package com.ari.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.ari.pojo.Role;
import com.ari.pojo.User;
import com.ari.service.Role.RoleServiceImpl;
import com.ari.service.user.UserService;
import com.ari.service.user.UserServiceImpl;
import com.ari.util.Constants;
import com.ari.util.PageSupport;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//servlet复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("修改密码Servlet ---start--");
        String method =req.getParameter("method");
        if (method.equals("savepwd")&&method!=null){
            this.updatePwd(req,resp);
        }else if (method.equals("pwdmodify")) {
            this.pwdModify(req,resp);
        }else if(method.equals("query")){
            this.query(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //修改密码
    protected void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("新密码Servlet ---start--");
        //从session中拿id
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        System.out.println(o);
        String newpassword = req.getParameter("newpassword");
        System.out.println("新密码"+ newpassword);
        boolean flag =false;
        System.out.println(o!=null);
        System.out.println(StringUtils.isNullOrEmpty(newpassword));

        if(o!=null&&newpassword!=null){
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User) o).getId(), newpassword);
            if (flag){
                req.setAttribute("messages","密码修改成功");
                //密码修改成功，移除当前Session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("messages","密码修改失败");
            }
        }else{
            req.setAttribute("messages", "新密码有问题");
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
    }
    //验证旧密码,session中有用户的密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("旧密码Servlet ---start--");
        //从Session里面拿ID;
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        System.out.println("旧密码" + oldpassword);
        //万能的Map : 结果集
        Map<String, String> resultMap = new HashMap<String, String>();

        if (o == null) { //Session失效了，session过期了
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) { //输入的密码为空
            resultMap.put("result", "error");
        } else {
            String userPassword = ((User) o).getUserPassword(); //Session中用户的密码
            if (oldpassword.equals(userPassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        //JSONArray 阿里巴巴的JSON工具类, 转换格式
            /*
            resultMap = ["result","sessionerror","result","error"]
            Json格式 = {key：value}
             */
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }
    /**
     * @description: 对用户进行查询【重点和难点】
     * @date 20/12/2 19:42
     * @Param: [req, resp]
     * @Return: void
     * 1.获取用户前端的数据（查询）
     * 2.判断请求是否需要执行，看参数的值判断
     * 3.为了实现分页，需要计算出当前页面和总页面，页面大小…
     * 4.用户列表展示
     * 5.返回前端
     */
    public void query(HttpServletRequest req, HttpServletResponse resp){

        //查询用户列表

        //从前端获取数据；
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;

        //第一次走这个请求，一定是第一页，页面大小固定的；
        int pageSize = 5; //可以把这个些到配置文件中，方便后期修改；
        int currentPageNo = 1;

        if (queryUserName ==null){
            queryUserName = "";
        }
        if (temp!=null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);  //给查询赋值！0,1,2,3
        }
        if (pageIndex!=null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户的总数 (分页：  上一页，下一页的情况)
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = ((int)(totalCount/pageSize))+1;

        //控制首页和尾页
        //如果页面要小于1了，就显示第一页的东西
        if (currentPageNo<1){
            currentPageNo = 1;
        }else if (currentPageNo>totalPageCount){ //当前页面大于了最后一页；
            currentPageNo = totalPageCount;
        }

        //获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList",userList);

        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
